package org.egedede.commons.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FileChooser extends JPanel implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9179960935496738400L;
	private final JTextField field;
	private final JButton chooser;

	public FileChooser() {
		super(new BorderLayout());
		field = new JTextField();
		chooser = new JButton("...");
		this.add(field);
		this.add(chooser, BorderLayout.EAST);
		chooser.addActionListener(this);
	}

	public void actionPerformed(final ActionEvent e) {
		final JFileChooser chooser = new JFileChooser();
		final String filePath = field.getText();
		if (filePath != null && filePath.length() > 0) {
			final File file = new File(filePath);
			if (file.exists()) {
				chooser.setSelectedFile(file);
			}
		}
		chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		final int showOpenDialog = chooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == showOpenDialog) {
			field.setText(chooser.getSelectedFile().getAbsolutePath());
		}
	}

	public String getFile() {
		return field.getText();
	}

	public void setFile(final String filePath) {
		if (new File(filePath).exists()) {
			field.setText(filePath);
		}
	}
}
